<?php

include('cfg/def.php');
include('cfg/cfg.php');

include_once("lib/logger.class.php");
include_once("lib/mysql.class.php");
include_once("lib/xtemplate.class.php");
include_once("models/m_user.class.php");
include_once("models/m_events.class.php");
include_once("models/m_event_links.class.php");
include_once("view/v_plans.class.php");
include_once("view/v_event.class.php");
include_once("view/v_messages.class.php");

Logger::$log_file = "logs/ajax";

MySQL::$url = $dburl;
MySQL::$encoding = $def_encoding;

session_start();

// Ответ только на запросы только после 
if($_SESSION["AJAXABLE"] != "YES")
{
	Logger::Write(__FILE__." line ".__LINE__, "ALARM! IP: ".$_SERVER["REMOTE_ADDR"]);
	Logger::Write(__FILE__." line ".__LINE__, '$_GET: '.print_r($_GET, true));
	Logger::Write(__FILE__." line ".__LINE__, '$_POST: '.print_r($_POST, true));
	
	header('Content-Type: text/plain; charset=utf-8');
	echo "try login as \nusername: dummy\npassword: stupid";
	exit();
}

if(DEBUG_MODE && FALSE)
{
	Logger::Write(__FILE__." line ".__LINE__, '$_GET: '.print_r($_GET, true));
	Logger::Write(__FILE__." line ".__LINE__, '$_POST: '.print_r($_POST, true));
}

$xml = $_POST["xml"];
$xml = stripslashes($xml);
Logger::Write(__FILE__." line ".__LINE__, 'AJAX REQUEST: '.$xml);

// Пакет ответа
$pack_a = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><pack />');
try
{
	// Пакет запроса
	$pack_r = new SimpleXMLElement($xml);
}
catch(Exception $e)
{
	show_error($e->getMessage());
	exit();
}

$actor = new mUser();
$actor->authorize();

if(!$actor->is_authorized())
{
	header('Content-Type: text/plain; charset=utf-8');
	echo 'Identification error';
	exit(100);
}

$actor->load();
$_SESSION['actor'] = $actor;

$ans = '';
$err = 0;
foreach($pack_r->request as $req)
{
	$obj_name  = $req["obj"];
	$act_type  = $req["act_type"];
	$page_type = $req["page_type"];
	$html      = $req["html"];
	
	$data = nodes2arr($req->data);
	$cond = nodes2arr($req->cond);
	$opt  = nodes2arr($req->option);

	// Logger::Write(__FILE__." line ".__LINE__, "OPT: ".print_r($opt, true));
	if(DEBUG_MODE)
		Logger::Write(__FILE__." line ".__LINE__, "object: ".$obj_name." action: ".$act_type);
	
	$ans = $pack_a->addChild("ans");
	$ans->addAttribute("req_id", $req["id"]);
	$ans_error = "0";
	
	switch($obj_name)
	{
		// СОБЫТИЯ ---------------------------------------------------
		case "event":
			switch($act_type)
			{
				// ЧТЕНИЕ
				case "sel":
					switch($html)
					{
						// ВЫВОД В ЛЕНТУ
						case "event-line":
							$events = $actor->more_events($opt["beg"], NUM_ROWS, $opt["dir"]);
							Logger::Write(__FILE__." line ".__LINE__, "event count: ".count($events));
							$html = vPlans::build_eventLine($events, $actor->id, TRUE);
							$html = htmlspecialchars($html);
							$html_box = $ans->addChild("html", '<![CDATA['.$html.']]>');
							// $html_box = $ans->addChild("html", $html);
							break;
					}
					break;
				
				// ВСТАВКА
				case "ins":
					$eid = mEvents::insert($actor->id, $data['date'], $data['time'], $data['access'], trim($data['text']));
					answerToEventAction($ans, $eid, $actor->id);
					break;
				
				// ИЗМЕНЕНИЕ
				case "upd":
					$res = mEvents::update($actor->id, $cond["event_id"], $data['date'], $data['time'], $data['access'], trim($data['text']));
					// Если ничего не удалили, то ошибка
					if($res)
					{
						answerToEventAction($ans, $cond['event_id'], $actor->id);
					}
					{
						$ans_error = "Ничего не изменено! Возможно у вас (ID:".$actor->id.") нет прав на изменение этого события (ID:".$cond['event_id'].").";
						Logger::Write(__FILE__." line ".__LINE__, "ERROR: ".$ans_error);
					}
					break;
				
				// УДАЛЕНИЕ
				case "del":
					$res = mEvents::delete($actor->id, $cond["event_id"]);
					// Если ничего не удалили, то ошибка
					if(!$res)
					{
						$ans_error = "Ничего не удалено! Возможно у вас (ID:".$actor->id.") нет прав на удаление этого события (ID:".$cond['event_id'].").";
						Logger::Write(__FILE__." line ".__LINE__, "ERROR: ".$ans_error);
					}
					break;
				
			}
			break;
		
		// СВЯЗЬ МЕЖДУ ПОЛЬЗОВАТЕЛЯМИ --------------------------------
		case "user-link":
			switch($act_type)
			{
				case "ins":
					$actor->add_link($data['user_id'], $data['link_type']);
					break;
				
				case "del":
					$actor->delete_link($data['user_id'], $data['link_type']);
					break;
			}
			$ans->addAttribute("result", 'OK');
			$ans->addAttribute("act", $act_type);
			$ans->addAttribute("user_id", $data['user_id']);
			$ans->addAttribute("link_type", $data['link_type']);
			break;
		
		// СВЯЗЬ ПОЛЬЗОВАТЕЛЕЙ И СОБЫТИЙ --------------------------------
		case "user-event":
			$categ = $data['categ'];
			switch($act_type)
			{
				case "ins":
					$new_id = mEventLinks::insert($data['event_id'], $categ, $data['note'], $actor);
					if($new_id == FALSE)
					{
						$err = "У Вас нет прав доступа к событию";
					}
					else
					{
						if($categ == 'COM')
						{
							$new_comment = mEventLinks::get($new_id);
							$html = vEvent::build_commentBox($new_comment, $actor);
							// Logger::Write(__FILE__." line ".__LINE__, $html);
							// $html = html_entity_decode($html);
							$html = htmlspecialchars($html);
							$com = $ans->addChild("comment", $html);
							// $com = $ans->addChild("comment", asCDATA($html));
							$com->addAttribute("id", $new_id);
						}
						else
							answerToEventAction($ans, $data['event_id'], $actor->id);
					}
					break;
				
				case "del":
					
					if($categ == 'COM')
					{
						mEventLinks::delete($event_id, $categ, $actor, $data['comment_id']);
					}
					else
					{
						delUserEventLink($actor, $data['event_id'], $categ);
						answerToEventAction($ans, $data['event_id'], $actor->id);
					}
					break;
			}
			break;
		
		// ПОЛЬЗОВАТЕЛЬ ----------------------------------------------
		case "user":
			break;
		
		// СООБЩЕНИЕ ----------------------------------------------
		case "message":
			switch($act_type)
			{
				case "ins":
					$new_id = mMessages::insert($actor->id, $data['user_id'], $data['categ'], $data['note']);
					$msg = mMessages::get($new_id);
					$html = vMessages::build_privateMessage($msg, $actor, null);
					$html = htmlspecialchars($html);
					$node = $ans->addChild("message", $html);
					$node->addAttribute("id", $new_id);
					break;
				
				case "del":
					$new_id = mMessages::delete($actor->id, $data['msg_id']);
					$ans->addAttribute("result", 'OK');
					$ans->addAttribute("msg_id", $data['msg_id']);
					break;
			}
			break;
		
		// ГОРОДА ----------------------------------------------------
		case "city":
			switch($act_type)
			{
				case "sel":
					$cities = getCities($cond["name"]);
					foreach($cities as $city)
					{
						$cityX = $ans->addChild("city");
						$cityX->addAttribute("id", $city["id"]);
						$cityX->addAttribute("name", $city["name"]);
						$cityX->addAttribute("region", $city["region"]);
						$cityX->addAttribute("population", $city["population"]);
					}
					break;
				
				case "set":
					$city_id = "0";
					if(!empty($data['city_id']))
						if(preg_match("/^\d+$/i", $data['city_id']))
							$city_id = $data['city_id'];
					
					$_SESSION['city_id'] = $city_id;
					$_SESSION['city'] = ($city_id == "0") ? null : $data['city'];
					setcookie('city_id', $_SESSION['city_id']);
					setcookie('city', $_SESSION['city']);
					break;
			}
			break;
		
		// Форимирование меню по AJAX запросу
		case "user-menu":
			$uid = $opt["user_id"];

			if($uid != $actor->id)
			{
				if(array_search($uid, $actor->links["WM"]))
					addMenuItem($ans, "Не следить", "", "#user_link-del-watch-".$uid);
				else
					addMenuItem($ans, "Cледить", "", "#user_link-ins-watch-".$uid);
					
				if(array_search($uid, $actor->links["FM"]))
					addMenuItem($ans, "Не доверять", "", "#user_link-del-friend-".$uid);
				else
					addMenuItem($ans, "Доверять", "", "#user_link-ins-friend-".$uid);
			}

			switch($page_type)
			{
				case "plans":
					addMenuItem($ans, "События", ROOT_URL."/".$uid."/plans/own", "");
					addMenuItem($ans, "Связи", ROOT_URL."/".$uid."/users", "");
					addMenuItem($ans, "Профиль", ROOT_URL."/".$uid."/users/info", "");
					break;
				
				case "users":
					addMenuItem($ans, "События", ROOT_URL."/".$uid."/plans", "");
					break;
			}
			break;
	}
	
	$ans->addAttribute("error", $ans_error);
}

$xml = $pack_a->asXML();
$xml = str_replace('&lt;![CDATA[', '<![CDATA[', $xml);
$xml = str_replace(']]&gt;', ']]>', $xml);

if(DEBUG_MODE)
{
	global $log_file_name;
	$fd = fopen($log_file_name.".xml.".date('Ymd').".log", "w+");
	// fwrite($fd, htmlspecialchars_decode($xml));
	fwrite($fd, $xml);
	fclose($fd);
}
// Logger::Write(__FILE__." line ".__LINE__, $xml);

header('Content-Type: text/xml; charset=utf-8');
echo $xml;

exit();

function asCDATA($str)
{
	return '&lt;![CDATA['.$str.']]&gt;';
}

function addMenuItem(&$ans, $text, $href, $name)
{
	$e = $ans->addChild("item");
	$e->addAttribute("text", $text);
	$e->addAttribute("href", $href);
	$e->addAttribute("name", $name);
}

function delUserEventLink($actor, $eid, $categ)
{
	mEventLinks::delete($eid, $categ, $actor);
	
	/*
	$db = MySQL::getInstance();
	$sql = "DELETE FROM event_users WHERE user_id = $uid AND event_id = $eid AND categ = '$categ';";
	if(LOG_SQL) Logger::Write(__FILE__." line ".__LINE__, $sql);
	$db->query($sql);
	*/
}

function answerToEventAction(&$ans, $event_id, $actor_id)
{
	$html = htmlEventBox($event_id, $actor_id);
	$html = htmlspecialchars($html);
	$e = $ans->addChild("event", $html);
	$e->addAttribute("id", $event_id);
}

function htmlEventBox($event_id, $actor_id)
{
	$event = mEvents::get($event_id);
	$events = array($event);
	$events = mEvents::add_details($events, $actor_id);
	
	return vPlans::build_eventBox($events[0], $actor_id);
}

function show_error($message)
{
	Logger::Write(__FILE__." line ".__LINE__, "ERROR: ".$message);
	header('Content-Type: text/xml; charset=utf-8');
	
	global $pack_a;
	$ans = $pack_a->addChild("ans");
	$ans->addAttribute("req_id", "0");
	$e = $ans->addChild("error", htmlspecialchars_decode($message));
	echo $pack_a->asXML();
	exit();
}

function getCities($cityName)
{
	$db = MySQL::getInstance();
	$cities = array();

	$sql =
		"SELECT c.id, c.name name, r.name region, c.population
		   FROM cities c, regions r
		  WHERE c.region_id = r.id
			AND c.name like '$cityName%'";

	if(LOG_SQL) Logger::Write(__FILE__." line ".__LINE__, $sql);
	$res = $db->query($sql);
	while($row = $db->fetch_assoc($res))
	{
		$cities[] = $row;
	}
	$db->free_result($res);
	return $cities;	
}

function attr2arr($node)
{
	$a = array();
	foreach($node->attributes() as $k => $v)
		$a[$k] = Utils::val($v);
	return $a;
}

function nodes2arr($nodes)
{
	$a = array();
	if(empty($nodes)) return $a;
	foreach($nodes as $child)
		$a[(string)$child["name"]] = html_entity_decode(Utils::val((string)$child["value"]), ENT_QUOTES);
	/*
	foreach($node->children() as $child)
		$a[(string)$child["name"]] = Utils::val((string)$child["value"]);
	*/
	return $a;
}